package  
{
	public class Boid
	{
		private const WIDTH:int = 20;
		private const HEIGHT:int = 20;
		
		public var mFriend:Boid = null;
		public var mEnemy:Boid = null;
		private var mSpeed:Number = 2;
		private var mBind:Vector3DExt = new Vector3DExt();
		private var mVec:Vector3DExt = new Vector3DExt();
		public var mPos:Vector3DExt = new Vector3DExt();
		
		public function Boid() 
		{
			mSpeed += (Rndm.random() - 0.5) * 2;
		}
		
		public function Update():void
		{
			Move(mFriend.mPos, 0.2 * mSpeed);
			Move(mEnemy.mPos, -0.1 * mSpeed);
			MoveToBind(mBind, 0.05 * mSpeed);
		}
		
		private var mSquareMoveToBindDist:Number = (HEIGHT/2)*(HEIGHT/2);
		private function MoveToBind(aTarget:Vector3DExt, aRatio:Number):void
		{
			mVec.x = aTarget.x - mPos.x;
			mVec.y = aTarget.y - mPos.y;
			mVec.z = aTarget.z - mPos.z
			
			aRatio *= (mVec.lengthSquared / mSquareMoveToBindDist);
			
			mVec.normalizeInto(mVec);
			
			mPos.x += mVec.x * aRatio;
			mPos.y += mVec.y * aRatio;
			mPos.z += mVec.z * aRatio;
		}
		
		private var mSquareMoveDist:Number = 0.8;
		private var mMoveLength:Number = 0;
		private function Move(aTarget:Vector3DExt, aRatio:Number):void 
		{
			mVec.x = aTarget.x - mPos.x;
			mVec.y = aTarget.y - mPos.y;
			mVec.z = aTarget.z - mPos.z;
			
			mMoveLength = mVec.normalizeInto(mVec);
			if (mMoveLength < mSquareMoveDist)
			{
				aRatio *= (mMoveLength / mSquareMoveDist) * 0.5;
			}
			
			mPos.x += mVec.x * aRatio;
			mPos.y += mVec.y * aRatio;
			mPos.z += mVec.z * aRatio;
		}
		
		public function SetBindPos(aX:Number, aY:Number, aZ:Number = 0):void
		{
			mBind.x = aX;
			mBind.y = aY;
			mBind.z = aZ;
		}
	}
}